package com.rivulet.dawn.web.controller.business;

import com.rivulet.dawn.api.common.TaskStatusEnum;
import com.rivulet.dawn.api.model.business.UploadTaskModel;
import com.rivulet.dawn.api.request.business.TagSaveRequest;
import com.rivulet.dawn.api.request.business.TagSearchRequest;
import com.rivulet.dawn.api.response.business.TagSearchResponse;
import com.rivulet.dawn.api.tools.FileTool;
import com.rivulet.dawn.api.tools.HttpTool;
import com.rivulet.dawn.api.tools.Page;
import com.rivulet.dawn.api.tools.ResultFul;
import com.rivulet.dawn.service.service.business.DictionaryService;
import com.rivulet.dawn.service.service.business.TagService;
import com.rivulet.dawn.service.service.business.UploadTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

@Api(value = "上传管理", tags = "上传管理")
@RestController
@RequestMapping("api/gateway/business/")
@Slf4j
public class UploadController {
    private final DictionaryService dictionaryService;
    private final UploadTaskService uploadTaskService;

    public UploadController(DictionaryService dictionaryService, UploadTaskService uploadTaskService) {
        this.dictionaryService = dictionaryService;
        this.uploadTaskService = uploadTaskService;
    }

    @RequestMapping(value = "/upload/uploadFile", method = RequestMethod.POST)
    public String uploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile multipartFile) {
        //取用户
        String username = "游客";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String nowDay = format.format(LocalDateTime.now());
        String fileName = multipartFile.getOriginalFilename();
        String fileDirPath = getDefaultUploadPath() + File.separator + nowDay;
        String filepath = fileDirPath + File.separator + fileName;
        File file = new File(filepath);
        File fileDir = new File(fileDirPath);
        long begin = System.currentTimeMillis();
        Integer status = TaskStatusEnum.WAITING.statusValue;
        String errorLog = "";
        try {
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            multipartFile.transferTo(file);
            status = TaskStatusEnum.SUCCESS.statusValue;
        } catch (Exception e) {
            log.error("UploadController.upload error, because {}", e.getMessage());
            errorLog = e.getMessage();
            status = TaskStatusEnum.ERROR.statusValue;
        }
        long end = System.currentTimeMillis();
        /**
         * 获取源文件的各项元数据
         */
        UploadTaskModel uploadTaskModel = new UploadTaskModel();
        String ip = HttpTool.getIpAddr(request);
        uploadTaskModel.setUploadIp(ip);
        long uploadDuration = end - begin;
        uploadTaskModel.setUploadDuration(uploadDuration);
        uploadTaskModel.setFilename(fileName);
        uploadTaskModel.setUploadPath(filepath);
        uploadTaskModel.setStatus(status);
        uploadTaskModel.setUploadTime(LocalDateTime.now());
        uploadTaskModel.setUploadUser(username);
        uploadTaskModel.setErrorMsg(errorLog);
        uploadTaskService.recordLog(uploadTaskModel);
        return filepath;
    }

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void downloadFile(HttpServletResponse response, @RequestParam("path") String path) {

        File file = new File(path);
        /**
         * 判断原始路径是否存在该文件
         *
         */
        if (!file.exists()) {
            response.setStatus(410);
            return;
        }
        /**
         * 下载功能的具体实现
         * 其中在文件输出时将文件名设为原始文件名
         */
        try {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", String.format("attachment;filename=\"%s\"", URLEncoder.encode(file.getName(), "utf-8")));
            InputStream inputStream = new FileInputStream(file);
            IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String getDefaultUploadPath() {
        String fileDirPath = null;
        Map<String, String> map = dictionaryService.getCodeName("filepath_setting");
        if (!CollectionUtils.isEmpty(map)) {
            if (Objects.nonNull(map.get("upload"))) {
                fileDirPath = map.get("upload");
            }
        }
        if (fileDirPath == null) {
            fileDirPath = FileTool.getWorkPath();
        }
        return fileDirPath;
    }
}
